#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/2/27 14:08
# @Author  : huidong.bai
# @File    : DelayFixture.py
# @Software: PyCharm
# @Mail    : MasterBai2018@outlook.com
import copy
import pdb
import pytest
import allure
from _pytest.fixtures import SubRequest
import os


@pytest.fixture(autouse=False, scope="function", name="RecordDelayFixture")
def record_delay_fixture(request: SubRequest):
    base_class = request.cls
    testcase_voice = request.cls.testcase.input.get('voice')
    case_expect = copy.deepcopy(request.cls.testcase.expect)
    # 解析音频边界
    base_class.voice_region_parse()

    yield
    result_callback_time = 0
    expect_msgType = case_expect[0].get('msgType')
    expect_channel = case_expect[0].get('channel')
    for result in base_class.callback_result:
        channel_id = str(result.get("channelId"))
        if result.get("resultType") == expect_msgType and expect_channel == channel_id:
            result_callback_time = result.get("recordTime")
    if base_class.tsa_session.speech_end_time:
        delay_time = {'result_callback_time': result_callback_time,
                              'speech_end_time': base_class.tsa_session.speech_end_time,
                              'voice': testcase_voice,
                              'expect_delay': request.cls.conveyor.case_header.delayTolerance.value}
        with open(os.path.join(base_class.conveyor.suite_dir, "delay.txt"), "a", encoding="utf-8", buffering=-1) as f:
            if delay_time.get('result_callback_time') == 0:
                actual_delay = float("inf")
            else:
                actual_delay = delay_time.get('result_callback_time')-delay_time.get('speech_end_time')
            if actual_delay >= int(delay_time.get('expect_delay')):
                is_pass = False
            else:
                is_pass = True
            f.write(f"Voice:{delay_time.get('voice')}\tExpectDelay:{delay_time.get('expect_delay')}\t ActualDelay:{actual_delay}\tIsPass: {is_pass}\n")
        base_class.voice_time_list.append([actual_delay, is_pass])
        base_class.tsa_session.speech_end_time = None
    base_class.callback_result.clear()


@pytest.fixture(autouse=False, scope="class", name="AnalysisDelayFixture")
def analysis_delay_fixture(request: SubRequest):
    base_class = request.cls
    with open(os.path.join(base_class.conveyor.suite_dir, "delay.txt"), "a", encoding="utf-8") as f:
        f.write("\n")
        f.write("VoiceInputPath\t\t\tExpectDelay\t\tActualDelay\t\tisPass\n")
        f.close()
    # 获取voiceRegionEnd时间
    yield
    # 获取最后统计数据
    with open(os.path.join(base_class.conveyor.suite_dir, "delay.txt"), "a", encoding="utf-8") as f:
        f.write(
            f"Total Cases: {len(base_class.voice_time_list)}, pass num: {len([x for x in base_class.voice_time_list if x[1] == True])}, Fail to pass num: {len([x for x in base_class.voice_time_list if x[1] == False])} \n")
        end_result_list = [x[0] for x in base_class.voice_time_list]
        num = sum(end_result_list) / len(end_result_list)
        rounded_num = round(num, 3)
        f.write(f"DelayMaxValue:{max(end_result_list)} , DelayMinValue:{min(end_result_list)} ,DelayAvgValue:{rounded_num}")
        f.write("\n")
        delay_txt_path = os.path.join(base_class.conveyor.suite_dir, "delay.txt")
        allure.attach.file(source=delay_txt_path, name="Delay", attachment_type=allure.attachment_type.TEXT)






